package lock_thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/4/29
 * Time:21:02
 * 用公平锁打印AABBCCDD
 **/
public class Demo4 {
    public static void main(String[] args) throws InterruptedException {
        //声明一个公平锁（设置为true）
        Lock lock = new ReentrantLock(true);

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                for (char item : "ABCD".toCharArray()
                ) {
                    lock.lock();
                    try {
                        System.out.println(item);
                    } finally {
                        lock.unlock();
                    }
                }
            }
        };
        Thread t1 = new Thread(runnable, "t1");
        Thread t2 = new Thread(runnable, "t2");

        Thread.sleep(10);
        t1.start();
        t2.start();
    }
}
